package com.rt.tmpt.security;

import com.rt.tmpt.security.handler.SecurityAction;
import com.rt.tmpt.security.exception.ValidateCodeException;
import com.rt.tmpt.security.handler.MyAuthenticationFailureHandler;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@Component
public class ImageCodeValidateFilter extends OncePerRequestFilter {


    //登录失败处理逻辑
    //@Autowired
    private MyAuthenticationFailureHandler authenticationFailureHandler=new MyAuthenticationFailureHandler();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if("/login".equalsIgnoreCase(request.getRequestURI())
            && request.getMethod().equalsIgnoreCase("post")){
            try {
                validate(request);
            }catch (AuthenticationException e){
                authenticationFailureHandler.onAuthenticationFailure(request,response,e);
                return;
            }
        }
        //pass the request
        filterChain.doFilter(request,response);
    }

    private void validate(HttpServletRequest request){
        String sessionCode = (String)request.getSession().getAttribute(SecurityAction.SESSION_KEY);
        String inputCode = request.getParameter("verifyCode");

        if(StringUtils.isBlank(inputCode)){
            throw new ValidateCodeException("验证码不能为空");
        }

        if(!inputCode.equalsIgnoreCase(sessionCode)){
            throw new ValidateCodeException("验证码输入错误");
        }
    }
}
